import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const user = {
  state: {
    info: {
      id:0,
      username:'',
      auth_key:'',
      status:0,
      updated_at:0,
      permissions:[],
    }
  },

  mutations: {
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_TOKEN: (state, token) => {
      state.info.auth_key = token
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        storage.set(ACCESS_TOKEN, userInfo.token, 7 * 24 * 60 * 60 * 1000)
        commit('SET_TOKEN', userInfo.token)
        resolve()
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        this._vm.$api.account('?expand=permissions').then(response => {
          console.log('account-->', response)

          commit('SET_INFO', response)

          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        storage.remove(ACCESS_TOKEN)
      })
    }
  }
}

export default user
